﻿using System;
using System.Net;
using System.Net.Mail;
using Webbness.Mvc.Config;

namespace Webbness.Mvc.Services
{
    public class SmtpService
    {
        private readonly string _message;
        private readonly string _subject;
        private readonly string _email;

        public SmtpService(string email, string subject, string message)
        {
            _email = email;
            _message = message;
            _subject = subject;
        }

        public bool SendMail(out string message)
        {
            var mail = new MailMessage
                           {
                               From = new MailAddress(SMTPSettings.SMTP.From),
                               Subject = _subject,
                               Body = _message
                           };

            mail.To.Add(new MailAddress(_email));

            if (String.IsNullOrEmpty(ApplicationSettings.CCEmailsTo) == false)
            {
                mail.CC.Add(new MailAddress(ApplicationSettings.CCEmailsTo));
            }

            try
            {
                var smtpClient = new SmtpClient
                                     {
                                         Host = SMTPSettings.SMTP.Network.Host,
                                         Port = SMTPSettings.SMTP.Network.Port,
                                         Credentials = new NetworkCredential(SMTPSettings.SMTP.Network.UserName, SMTPSettings.SMTP.Network.Password)
                                     };

                smtpClient.Send(mail);
            }
            catch (Exception ex)
            {
                message = ex.ToString();
                return false;
            }
            message = "Email sent.";
            return true;
        }
    }
}